package com.blb.shiro;

import java.util.Collection;
import java.util.List;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.blb.entity.User;
import com.blb.entity.UserExample;
import com.blb.mapper.UserMapper;

public class MyRealm extends AuthorizingRealm {

    @Autowired
    private UserMapper userMapper;

    /**
     * 登录认证
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        //获取当前用户名
        String username = (String) token.getPrincipal();

        //获取user对象
        UserExample userExample = new UserExample();
        userExample.createCriteria().andUsernameEqualTo(username);
        List<User> list = userMapper.selectByExample(userExample);

        //判断用户是否存在
        if (list.isEmpty()) {
            return null;
        }
        User user = list.get(0);

        //用户是否被冻结
        if (user.getState() == -1) {
            throw new LockedAccountException();
        }

        //user.getSalt()
        //用户信息，密码，getName();
        return new SimpleAuthenticationInfo(user, user.getPassword(), ByteSource.Util.bytes(user.getSalt()), getName());
    }

    /**
     * 授权
     * 根据用户名获得角色信息和权限
     *
     * @param arg0
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
        User user = (User) principal.getPrimaryPrincipal();
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();

        String username = user.getUsername();

        System.out.println("111111111111111111111");

        //根据用户名获取角色名
        List<String> roles = userMapper.getRoles(username);
        simpleAuthorizationInfo.addRoles(roles);
        //权限
        List<String> permission = userMapper.getStringPermission(roles);
        simpleAuthorizationInfo.addStringPermissions(permission);


        return simpleAuthorizationInfo;
    }


}
